<template>
  <div class="permission">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="box">
        <div class="function">
          <div class="box-main">
            <div class="pc">
              <h3>PC端（包含功能模块、操作按钮配置）</h3>
              <el-tree
                class="body"
                ref="treeRefPc"
                :data="state.dataPc"
                show-checkbox
                :default-expand-all="false"
                node-key="id"
                highlight-current
                :props="defaultProps"
                :default-checked-keys="checkTreePc"
              />
            </div>

            <div class="small-routine">
              <h3>小程序（包含功能模块、操作按钮配置）</h3>
              <!-- <div class="body">
                <el-checkbox-group class="checkbox-group" v-model="check">
                  <el-checkbox v-for="(item, index) in checkList" :label="item" />
                </el-checkbox-group>
              </div> -->
              <el-tree
                class="body"
                ref="treeRefSmall"
                :data="state.dataSmall"
                show-checkbox
                :default-expand-all="false"
                node-key="id"
                highlight-current
                :props="defaultProps2"
                :default-checked-keys="checkTreeSmall"
              />
            </div>
          </div>
          <div class="buttons">
            <el-button @click="cancel()">取消</el-button>
            <el-button type="primary" @click="submitForm()"> 确定 </el-button>
          </div>
        </div>
        <p></p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElAlert, ElMessage, ElTree } from 'element-plus'
import { menuTreeList, setRight } from '/@/api/setting/index'
import { useRoute } from 'vue-router'
import routes from '/@/router'
const route = useRoute()
// const form = ref(JSON.parse(route.query.form as string))
const formId = ref(route.query.form).value

// const checkList = ref(['selected and disabled', 'Option A'])
// const check = ref([''])
//树默认选中-pc
const checkTreePc = ref([''])
//树默认选中-小程序
const checkTreeSmall = ref([''])

// interface Tree {
//   id: number
//   label: string
//   children?: Tree[]
// }
interface Tree {
  id: string
  menuName: string
  children?: Tree[]
}

const treeRefPc = ref<InstanceType<typeof ElTree>>()
const treeRefSmall = ref<InstanceType<typeof ElTree>>()

const defaultProps2 = {
  children: 'children',
  label: 'menuName'
}

const defaultProps = {
  children: 'children',
  label: 'menuName',
  disabled: 'disabled'
}

const state = reactive<any>({
  dataPc: [],
  dataSmall: []
})

// 页面加载时
onMounted(async () => {
  // onMounted(() => {
  let params = { roleId: formId, terminalType: 1 }
  state.dataPc = await getTreeList(params)
  checkedNodesPc(state.dataPc)
  disabledNodesPc(state.dataPc)

  let params2 = { roleId: formId, terminalType: 2 }
  state.dataSmall = await getTreeList(params2)
  checkedNodesSmall(state.dataSmall)
  // getTreeListSmall(params2)
})

const getTreeList = (params: any) => {
  return new Promise<void>((resolve, reject) => {
    menuTreeList(params).then((res) => {
      if (res.code == 0) {
        resolve(res.data)
      }
    })
  })
}

const getTreeListPc = (params: any) => {
  menuTreeList(params).then((res) => {
    if (res.code == 0) {
      state.dataPc = res.data
      checkedNodesPc(state.dataPc)
    }
  })
}

const disabledNodesPc = (list: any) => {
  for (const item of list) {
    if (list.forbiddenFlag == 1) {
      list.disabled = true
    }
    if (item.children) {
      for (let i = 0; i < item.children.length; i++) {
        const element = item.children[i]
        if (element.forbiddenFlag == 1) {
          element.disabled = true
        }
        if (element.children) {
          for (let j = 0; j < element.children.length; j++) {
            const el = element.children[j]
            if (el.forbiddenFlag == 1) {
              el.disabled = true
            }
          }
        }
      }
    }
  }
  state.dataPc = list
}

const checkedNodesPc = (itemList: any) => {
  for (const item of itemList) {
    if (item.chooseFlag === 1) {
      let flag = true
      let itemFlag = true
      if (item.children) {
        checkedNodesPc(item.children)
        for (let i = 0; i < item.children.length; i++) {
          const element = item.children[i]
          if (element.chooseFlag == 0) {
            flag = false
          } else {
            if (element.children) {
              for (let i = 0; i < element.children.length; i++) {
                const e = element.children[i]
                if (e.chooseFlag == 0) {
                  itemFlag = false
                }
              }
              if (itemFlag) {
                checkTreePc.value.push(element.id)
              }
            }
          }
        }
      }
      if (flag && itemFlag) {
        checkTreePc.value.push(item.id)
      }
    }
  }
}

const getTreeListSmall = (params: any) => {
  menuTreeList(params).then((res) => {
    if (res.code == 0) {
      state.dataSmall = res.data
      checkedNodesSmall(state.dataSmall)
    }
  })
}

const checkedNodesSmall = (itemList: any) => {
  for (const item of itemList) {
    if (item.chooseFlag === 1) {
      checkTreeSmall.value.push(item.id)
    }
    if (item.children != null && item.children != undefined) {
      checkedNodesSmall(item.children)
    }
  }
}

//取消按钮
const cancel = () => {
  //返回上一级页面
  routes.push({
    name: 'settingRole'
  })
}

//保存按钮
const submitForm = () => {
  let params: any = []
  let arr: any = []
  arr = arr.concat(
    treeRefPc.value!.getCheckedKeys(false),
    treeRefPc.value!.getHalfCheckedKeys()
  )
  params = params.concat(arr, treeRefSmall.value!.getCheckedKeys(false))
  if (params.length == 0) {
    ElMessage.warning('请先配置功能权限')
  } else {
    setRight(formId, params).then((res) => {
      if (res.code == 0) {
        routes.push({
          name: 'settingRole'
        })
        ElMessage({
          type: 'success',
          message: '保存成功'
        })
      }
    })
  }
}
</script>

<style scoped lang="scss">
.permission {
  font-size: var(--el-font-size-base);

  h3 {
    height: 40px;
    background: #f0f0f0;
    color: #2b2b2b;
    // font-size: 14px;
    line-height: 40px;
    text-align: center;
  }

  .box {
    display: flex;

    .function {
      display: flex;
      flex-direction: column;
      flex-grow: 1;

      .box-main {
        display: flex;

        .body {
          min-height: 410px;
          border: 1px solid rgba(224, 224, 224, 1);
          padding-top: 16px;
        }

        .pc {
          flex-grow: 1;
        }

        .small-routine {
          flex-grow: 1;
          margin-left: 12px;

          .checkbox-group {
            display: flex;
            flex-direction: column;
            margin-left: 24px;
          }
        }
      }

      .buttons {
        align-self: flex-end;
        margin-top: 24px;
      }
    }

    p {
      flex-grow: 8;
    }
  }
}
</style>
